<template>
  <div>
    姓名: <input v-model.trim="form.name" type="text"><br>
    年龄: <input v-model.number="form.age" type="text"><br>
    性别:
    <select v-model="form.gender">
      <option value="男">男</option>
      <option value="女">女</option>
    </select><br>
    <button @click="add">添加</button>
    <button @click="modify">修改</button>
    <br>
    <table border>
      <thead>
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(item, index) in arr" :key="item.id">
          <td>{{ index + 1 }}</td>
          <td>{{ item.name }}</td>
          <td>{{ item.age }}</td>
          <td>{{ item.gender }}</td>
          <td>
            <button>删除</button>&nbsp;
            <button @click="edit(item.id)">编辑</button>
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script>
export default {
  data() {
    
    return {
      form: {
      name:'',
      age:'',
      gender:'',
      id:''
      },
      arr: [
        { id: 11, name: 'Tom', gender: '男', age: 19 },
        { id: 22, name: 'Jone', gender: '女', age: 21 },
      ]
    }
  },
  methods: {
   
    add(){
       const {name,age,gender} = this.form
      //先进行非空校验
      if(this.name === '' || this.age === '' || this.gender === '') return alert('请输入数据')
        //添加功能
        this.arr.push({
          name,
          age,
          gender,
          id:Date.now()
          },
        )
        //清空表单
        // 
        this.form =  {
          name:'',
          age:'',
          gender:''

        }
    },
    edit(id){
      
      const obj = this.arr.find(item => item.id === id)
      this.form = {...obj}

    },
    modify(){
      // 1.找到当前要修改数据 id
      const id = this.form.id
      // 2.根据id找到对应的数据
      const obj = this.arr.find(item => item.id === id)
      // 3.修改数据
      obj.name = this.form.name
      obj.age = this.form.age
      obj.gender = this.form.gender

       this.form =  {
          name:'',
          age:'',
          gender:''

        }
    }
    //清空表单数据
   
  }
}
</script>

<style scoped>
table {
  /* border: 1px solid black; */
  border-collapse: collapse;
}
td, th {
  padding: 10px;
}
</style>
